package leetcode_bin_tree_test;

import bin_tree.TreeNode;

import java.util.Arrays;

/**
 * 将有序数组转换为 二叉搜索树
 */
public class ConvertOrderedToBinarySearch {
    public static TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 0) {
            return null;
        }
        // 高度差的绝对值不超过 1
        int len = nums.length;
        // 设置中间值为根结点
        TreeNode root = new TreeNode(nums[len / 2]);
        int[] left = Arrays.copyOfRange(nums, 0, len / 2);
        int[] right = Arrays.copyOfRange(nums, len / 2 + 1, len);
        root.left = sortedArrayToBST(left);
        root.right = sortedArrayToBST(right);
        return root;
    }

    public static void main(String[] args) {
        int[] nums = new int[] {-10, -3, 0, 5, 9};
        TreeNode root = sortedArrayToBST(nums);
    }
}
